package com.sixmac.service.impl;

import com.sixmac.core.plugins.dao.Blade;
import com.sixmac.core.plugins.dao.Db;
import com.sixmac.core.toolbox.ajax.AjaxResult;
import com.sixmac.core.toolbox.kit.StrKit;
import com.sixmac.core.toolbox.support.Convert;
import com.sixmac.model.User;
import com.sixmac.service.CategoryService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by admin on 2018/6/9.
 */
@Service
public class CategoryServiceImpl implements CategoryService {

    private List<Map> getFirstCategory() {
        String sql = "select * from t_category where pid !=0 and defaultValue=1";
        return Db.selectList(sql);
    }


    private List<Map> getCategoryIds(String categoryIds) {
        String sql = "select * from t_category where id in (" + categoryIds + ")";
        return Db.selectList(sql);
    }

    public String getFirstCategoryIds() {
        List<Map> maps = this.getFirstCategory();
        StringBuilder sb = new StringBuilder();
        for (Map m : maps) {
            sb.append(m.get("id"));
            sb.append(",");
        }
        return sb.substring(0, sb.length() - 1).toString();

    }


    @Override
    public AjaxResult getCategory(Integer userId) {
        AjaxResult res = new AjaxResult();
        List<Map> maps;
        User user = Blade.create(User.class).findById(userId);
        String categoryIds = user.getCategoryIds();
        if (categoryIds==null||StrKit.isEmpty(categoryIds.trim())) {
            maps = this.getFirstCategory();
        } else {
            maps = this.getCategoryIds(categoryIds);
        }
        return res.setData(maps);
    }
}
